package com.hsogoo.ultraman;

import com.hsogoo.ultraman.container.ConfigContainer;
import com.hsogoo.ultraman.enums.ConfigFileType;

public class ConfigService {
    private static final ConfigService instance = new ConfigService();

    private volatile ConfigFactoryRegistry configFactoryRegistry;

    private ConfigFactoryRegistry getConfigFactoryRegistry() {
        if (configFactoryRegistry == null) {
            synchronized (this) {
                if (configFactoryRegistry == null) {
                    configFactoryRegistry = ConfigContainer.getBean(ConfigFactoryRegistry.class);
                }
            }
        }

        return configFactoryRegistry;
    }

    /**
     * Get the config instance for the namespace.
     *
     * @param namespace the namespace of the config
     * @return config instance
     */
    public static Config getConfig(String namespace) {
        return instance.getConfigFactoryRegistry().getFactory(namespace).getConfig(namespace);
    }

    static void setConfig(String namespace, final Config config) {
        instance.getConfigFactoryRegistry().register(namespace, new ConfigFactory() {
            @Override
            public Config getConfig(String namespace) {
                return config;
            }

        });
    }

    static void setConfigFactory(String namespace, ConfigFactory factory) {
        instance.getConfigFactoryRegistry().register(namespace, factory);
    }

}
